package org.light.simpleauth.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.complexverb.Assign;
import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Dropdown;
import org.light.domain.Field;
import org.light.domain.FieldSerialComparator;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.StatementList;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.oracle.generator.MybatisOracleSqlReflector;
import org.light.utils.DomainUtil;
import org.light.utils.FieldUtil;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;
import org.light.verb.ExistsByName;
import org.light.verb.FindByName;

public class AddUser extends Verb implements EasyUIPositions {
	protected Domain roleDomain;

	public Domain getRoleDomain() {
		return roleDomain;
	}

	public void setRoleDomain(Domain roleDomain) {
		this.roleDomain = roleDomain;
	}

	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Add" + StringUtil.capFirst(this.domain.getStandardName()));
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, "tx","*sql.Tx"));
			method.addSignature(new Signature(3, this.domain.getLowerFirstDomainName(),this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()));
			method.setReturnType(this.domain.getDomainId().getRawType());
			
			List<Writeable> sList = new ArrayList<Writeable>();
			
			sList.add(new Statement(1000L,1,"salt := utils.GenerateSalt(db)"));
			sList.add(new Statement(2000L,1,"encrpt := utils.MultiSha1("+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"(), salt, 3)"));
			
			if (StringUtil.isBlank(this.getDbType())||this.getDbType().equalsIgnoreCase("MariaDB")||this.getDbType().equalsIgnoreCase("MySQL")) {
				sList.add(new Statement(3000L,1,"sql := \""+MybatisSqlReflector.generateInsertSql(domain)+"\""));
			}else if (this.getDbType().equalsIgnoreCase("PostgreSQL")||this.getDbType().equalsIgnoreCase("pgsql")) {
				sList.add(new Statement(3000L,1,"sql := \""+PgsqlReflector.generateInsertSql(domain)+"\""));
			}else if (this.getDbType().equalsIgnoreCase("Oracle")) {
				sList.add(new Statement(3000L,1,"sql := \""+MybatisOracleSqlReflector.generateInsertSql(domain)+"\""));
			}
			
			sList.add(new Statement(4000L,1,"stmt, err := db.Prepare(sql)"));
			sList.add(new Statement(5000L,1,"defer stmt.Close()"));
			sList.add(new Statement(6000L,1,"if err != nil {"));
			sList.add(new Statement(7000L,2,"panic(err)"));
			sList.add(new Statement(8000L,1,"}"));

			StringBuilder sb = new StringBuilder();
			for (Field f:domain.getFieldsWithoutId()) {
				if (f.getFieldName().equals(this.domain.findFieldByFixedName("password").getFieldName())) {
					sb.append("encrpt").append(",");
				}else if (f.getFieldName().equals(this.domain.findFieldByFixedName("salt").getFieldName())) {
					sb.append("salt").append(",");
				}else if (f.getFieldName().equals(this.domain.findFieldByFixedName("loginFailure").getFieldName())) {
					sb.append("0").append(",");
				}else if ("bool".equalsIgnoreCase(f.getFieldType())&&"oracle".equalsIgnoreCase(this.domain.getDbType())) {
					sb.append("utils.ParseBooltoInt("+this.domain.getLowerFirstDomainName()).append(".Get").append(f.getCapFirstFieldName()).append("()),");
				}else if ("datetime".equalsIgnoreCase(f.getFieldType())||"date".equalsIgnoreCase(f.getFieldType())){
					sb.append(this.domain.getLowerFirstDomainName()).append(".Get").append(f.getCapFirstFieldName()).append("().SqlString(),");
				}else {
					sb.append(this.domain.getLowerFirstDomainName()).append(".Get").append(f.getCapFirstFieldName()).append("(),");
				}
			}
			String execStr = sb.toString();
			execStr = execStr.substring(0,execStr.length()-1);
			sList.add(new Statement(9000L,1,"result, err := stmt.Exec("+execStr+")"));
			
			sList.add(new Statement(11000L,1,"if err != nil {"));
			sList.add(new Statement(12000L,2,"panic(err)"));
			sList.add(new Statement(13000L,1,"}"));
			sList.add(new Statement(14000L,1,"var returnid int64"));
			sList.add(new Statement(15000L,1,"returnid, err = result.LastInsertId()"));
			sList.add(new Statement(16000L,1,"return returnid"));
			
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("void"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("add"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("bool"));
			method.setThrowException(true);
			method.addAdditionalImport("java.util.List");
			method.addAdditionalImport(this.domain.getPackageToken()+ "."+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix());
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), this.domain.getType()));
			return method;
		}
	}

	@Override
	public Method generateServiceImplMethod() throws Exception  {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Add" + StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(this.domain.getDomainId().getRawType());
			method.addSignature(
					new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), new Type(this.domain.getDomainSuffix()+"."+this.domain.getType())));
		
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"db := database.DB"));
			sList.add(new Statement(2000L,1,"tx, err := db.Begin()"));
			sList.add(new Statement(3000L,1,"if err != nil {"));
			sList.add(new Statement(4000L,2,"panic(err)"));
			sList.add(new Statement(5000L,1,"}"));
			sList.add(new Statement(6000L,1,"retVal := "+this.domain.getDaoimplSuffix()+".Add"+this.domain.getCapFirstDomainName()+"(db, tx, "+this.domain.getLowerFirstDomainName()+")"));
			sList.add(new Statement(7000L,1,"tx.Commit()"));
			sList.add(new Statement(8000L,1,"return retVal"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	
	public AddUser(Domain domain,Domain roleDomain) throws ValidateException{
		super();
		this.domain = domain;
		this.roleDomain = roleDomain;
		this.dbType = domain.getDbType();
		this.denied = domain.isVerbDenied("Add");
		this.setVerbName("Add"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("新增");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("Add");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		Method method = new Method();
		method.setStandardName("Add" + StringUtil.capFirst(this.domain.getStandardName()));
		method.addSignature(new Signature(1,"c","*gin.Context"));
		method.addAdditionalImport(DomainUtil.packagetokenToGoPackageFolder(this.domain.getProjectName(),"pkg.errno"));
		method.addAdditionalImport("net/http");
		
		List<Writeable> sList = new ArrayList<Writeable>();
		sList.add(new Statement(1000L,1,"var r "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
		sList.add(new Statement(2000L,0,""));
		sList.add(new Statement(3000L,1,"if c.ShouldBindJSON(&r) != nil {"));
		sList.add(new Statement(4000L,2,"SendResponse(c, errno.ErrBind, nil, 0 ,false)"));
		sList.add(new Statement(5000L,2,"return"));
		sList.add(new Statement(6000L,1,"}"));
		sList.add(new Statement(7000L,1,""));
		
		ExistsByName exists = new ExistsByName(this.domain);
		sList.add(new Statement(8000L,1,""+this.domain.getLowerFirstDomainName()+"Exists := "+this.domain.getServiceimplSuffix()+"."+StringUtil.capFirst(exists.getVerbName())+"(r.Get"+this.domain.getDomainName().getCapFirstFieldName()+"())"));
		sList.add(new Statement(9000L,1,"if ("+this.domain.getLowerFirstDomainName()+"Exists){"));
		sList.add(new Statement(10000L,2,"c.JSON(http.StatusOK, gin.H{"));
		if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
			sList.add(new Statement(11000L,3,"\"error\": \""+this.domain.getText()+" exists.\","));
		} else {
			sList.add(new Statement(11000L,3,"\"error\": \""+this.domain.getText()+"已存在\","));
		}
		sList.add(new Statement(12000L,3,"\"success\": false,"));
		sList.add(new Statement(13000L,2,"})"));
		sList.add(new Statement(14000L,2,"return"));
		sList.add(new Statement(15000L,1,"}"));
		
		long serial = 16000L;
		boolean imageExists = this.domain.containsImage();
		for (Field f:this.domain.getPlainFields()) {
			if (f.getFieldType().equalsIgnoreCase("image")) {
				sList.add(new Statement(serial,1,"if temp"+this.domain.getCapFirstDomainName()+".Get"+f.getCapFirstFieldName()+"() != nil {"));
				sList.add(new Statement(serial+1000L,2,"r.Set"+f.getCapFirstFieldName()+"(temp"+this.domain.getCapFirstDomainName()+".Get"+f.getCapFirstFieldName()+"())"));
				sList.add(new Statement(serial+2000L,1,"}"));
				serial += 3000L;
			}				
		}
		sList.add(new Statement(serial,1,this.domain.getServiceimplSuffix()+".Add"+this.domain.getCapFirstDomainName()+"(r)"));
		serial += 1000L;
		for (Field f:this.domain.getPlainFields()) {
			if (f.getFieldType().equalsIgnoreCase("image")) {
				sList.add(new Statement(serial,1,"temp"+this.domain.getCapFirstDomainName()+".Set"+f.getCapFirstFieldName()+"(nil)"));
				serial += 2000L;
			}
		}	
	
		FindByName findRole = new FindByName(this.roleDomain);
		FindByName findUser = new FindByName(this.domain);
		Assign assign = new Assign(this.domain,this.roleDomain);
		sList.add(new Statement(serial+1000L,1,this.roleDomain.getLowerFirstDomainName() + " := "+this.domain.getServiceimplSuffix()+"."+StringUtil.capFirst(findRole.getVerbName())+"(\"user\")"));
		sList.add(new Statement(serial+2000L,1,""+this.domain.getLowerFirstDomainName()+" := "+this.domain.getServiceimplSuffix()+"."+StringUtil.capFirst(findUser.getVerbName())+"(r.Get"+this.domain.getDomainName().getCapFirstFieldName()+"())"));
		sList.add(new Statement(serial+3000L,1,this.domain.getServiceimplSuffix()+"."+StringUtil.capFirst(assign.getVerbName())+"("+this.domain.getLowerFirstDomainName()+".Get"+this.domain.getDomainId().getCapFirstFieldName()+"(),[] int64 {"+this.roleDomain.getLowerFirstDomainName()+".Get"+this.roleDomain.getDomainId().getCapFirstFieldName()+"()})"));

		sList.add(new Statement(serial+4000L,1,"SendResponse(c, nil, r, 0, true)"));
		method.setMethodStatementList(WriteableUtil.merge(sList));
		return method;
	}
	
	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied) return null;
		else {
			JavascriptBlock block = new JavascriptBlock();
			block.setSerial(100);
			block.setStandardName("add"+domain.getCapFirstDomainName());
			StatementList sl = new StatementList();
			sl.add(new Statement(1000,0, "{"));
			if (this.domain.getLanguage().equalsIgnoreCase("english")) {
				sl.add(new Statement(2000, 1, "text:'Add',"));
			}else {
				sl.add(new Statement(2000,1, "text:'新增',"));
			}
			sl.add(new Statement(3000,1, "iconCls:'icon-add',"));
			sl.add(new Statement(4000,1, "handler:function(){"));
			sl.add(new Statement(5000,2, "$('#wadd"+this.domain.getCapFirstDomainName()+"').window('open');"));
			sl.add(new Statement(6000,1, "}"));
			sl.add(new Statement(7000,0, "}"));
			block.setMethodStatementList(sl);
			return block;			
		}
	}
	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied) return null;
		else {
			Domain domain = this.domain;
			JavascriptMethod method = new JavascriptMethod();
			method.setSerial(200);
			method.setStandardName("add"+domain.getCapFirstDomainName());
			
			StatementList sl = new StatementList();
			
			sl.add(new Statement(1000L,1,"if ($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").val()!=$(\"#ff\").find(\"#confirm"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"\").val()){"));
			if ("english".equalsIgnoreCase(this.domain.getLanguage())) {
				sl.add(new Statement(2000L,2,"$.messager.alert(\"Error\",\"Password did not match.\",\"error\");"));
			}else {
				sl.add(new Statement(2000L,2,"$.messager.alert(\"错误\",\"密码不匹配！\",\"error\");"));
			}
			sl.add(new Statement(3000L,2,"return;"));
			sl.add(new Statement(4000L,1,"}"));
			
			sl.add(new Statement(5000,1, "if ($(\"#ff\").form(\"validate\")) {"));
			sl.add(new Statement(6000,2, "$.ajax({"));
			sl.add(new Statement(7000,3, "type: \"post\","));
			sl.add(new Statement(8000,3, "url: \"../"+this.domain.getControllerPackagePrefix()+domain.getLowerFirstDomainName()+domain.getControllerNamingSuffix()+"/add"+domain.getCapFirstDomainName()+"\","));
			sl.add(new Statement(9000,3, "data: JSON.stringify({"));
			
			sl.add(new Statement(10000,4, this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+":$(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("userName").getLowerFirstFieldName()+"\").textbox(\"getValue\"),"));
			sl.add(new Statement(11000,4, this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+":hex_sha1($(\"#ff\").find(\"#"+this.domain.findFieldByFixedName("password").getLowerFirstFieldName()+"\").textbox(\"getValue\")),"));
			
			Set<Field> normalFields = new TreeSet<>(new FieldSerialComparator());
			normalFields.addAll(domain.getFieldsWithoutId());
			Set<Field> deniedFields = new TreeSet<>(new FieldSerialComparator());
			deniedFields.add(this.domain.findFieldByFixedName("userName"));
			deniedFields.add(this.domain.findFieldByFixedName("password"));
			deniedFields.add(this.domain.findFieldByFixedName("salt"));
			deniedFields.add(this.domain.findFieldByFixedName("loginFailure"));
			normalFields = FieldUtil.filterDeniedFields(normalFields,deniedFields);
			long serial = 12000;
			for (Field f:normalFields){
				if (f instanceof Dropdown) {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":parseIntNeg($(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").combobox(\"getValue\")),"));
				} else if (f.getFieldType().equalsIgnoreCase("bool")) {
					sl.add(new Statement(serial, 3,
							f.getLowerFirstFieldName() + ":parseBoolean($(\"#ff\").find(\"input[name='"
									+ f.getLowerFirstFieldName() + "']:checked\").val()),"));
				} else if (f.getFieldType().equalsIgnoreCase("int")||f.getFieldType().equalsIgnoreCase("int32")||f.getFieldType().equalsIgnoreCase("int64")) {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":parseInt($(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val()),"));
				} else if (f.getFieldType().equalsIgnoreCase("float")||f.getFieldType().equalsIgnoreCase("float64")||f.getFieldType().equalsIgnoreCase("float32")) {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":parseFloat($(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val()),"));
				} else if (f.isTextarea()) {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":$(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val(),"));
				} else if (f.getFieldType().equalsIgnoreCase("date")) {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":$(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val().trim(),"));
				} else if (f.getFieldType().equalsIgnoreCase("datetime")) {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":$(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val().trim(),"));
				} else {
					sl.add(new Statement(serial, 3, f.getLowerFirstFieldName() + ":$(\"#ff\").find(\"#"
							+ f.getLowerFirstFieldName() + "\").val(),"));
				}
				serial += 1000;
			}				
			sl.add(new Statement(serial,3, "}),"));
			sl.add(new Statement(serial+1000,3, "dataType: 'json',"));
			sl.add(new Statement(serial+2000,3, "contentType:\"application/json;charset=UTF-8\","));
			sl.add(new Statement(serial+3000,3, "success: function(data, textStatus) {"));
			sl.add(new Statement(serial+4000,4, "if (data.success) {"));
			sl.add(new Statement(serial+5000,5, "$('#ff').form('clear');"));
			sl.add(new Statement(serial+6000,5, "$(\"#ff\").find(\"input[name='"+domain.getActive().getLowerFirstFieldName()+"']\").get(0).checked = true;"));
			sl.add(new Statement(serial+7000,5, "$(\"#wadd"+domain.getCapFirstDomainName()+"\").window('close');"));
			sl.add(new Statement(serial+8000,5, "$(\"#dg\").datagrid(\"load\");"));
			sl.add(new Statement(serial+9000,4, "}"));
			sl.add(new Statement(serial+10000,4, "},"));
			sl.add(new Statement(serial+11000,3, "complete : function(XMLHttpRequest, textStatus) {"));
			sl.add(new Statement(serial+12000,3, "},"));
			sl.add(new Statement(serial+13000,3, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
			sl.add(new Statement(serial+14000,4, "alert(\"Error:\"+textStatus);"));
			sl.add(new Statement(serial+15000,4, "alert(errorThrown.toString());"));
			sl.add(new Statement(serial+16000,3, "}"));
			sl.add(new Statement(serial+17000,2, "});"));
			sl.add(new Statement(serial+18000,1, "}"));
			
			method.setMethodStatementList(sl);
			return method;	
		}
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Add" + StringUtil.capFirst(this.domain.getStandardName()));
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getLowerFirstDomainName(),this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()));
			method.setReturnType(this.domain.getDomainId().getRawType());
			
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"newIndex := max"+this.domain.getCapFirstDomainName()+"Id() + 1"));
			sList.add(new Statement(2000L,1,""+this.domain.getLowerFirstDomainName()+".Set"+this.domain.getDomainId().getCapFirstFieldName()+"(newIndex)"));
			sList.add(new Statement(3000L,1,""+this.domain.getLowerFirstDomainName()+"Db = append("+this.domain.getLowerFirstDomainName()+"Db, "+this.domain.getLowerFirstDomainName()+")"));
			sList.add(new Statement(4000L,1,"return newIndex"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public Method generateDummyServiceImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Add" + StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(this.domain.getDomainId().getRawType());
			method.addSignature(
					new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), new Type(this.domain.getDomainSuffix()+"."+this.domain.getType())));
		
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"db := database.DB"));
			sList.add(new Statement(6000L,1,"retVal := "+this.domain.getDaoimplSuffix()+".Add"+this.domain.getCapFirstDomainName()+"(db, "+this.domain.getLowerFirstDomainName()+")"));
			sList.add(new Statement(8000L,1,"return retVal"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
}
